/*
 *	Author: Vitaly Rozhkov
 *	vitaly.rozhkov@gmail.com
 *  http://bookvarius.livejournal.com
 *
*/

#include "Batch Helpers/include/common.jsx"

var configFilePath =  app.path.toString() + "/Presets/Scripts/Batch Helpers/config/Make9PatchBorderCfg.txt";
var settings;

function _readSettings(silent){
	settings = ConfigRead(configFilePath);
	if(	null == settings || 
		(!settings['borderHorisontalWidth'].isInteger() || 
		!settings['borderVerticalWidth'].isInteger() )
	)
	{
		if(!silent){
			alert('Use default settings: 5x3');
		}
		if(null == settings){
			settings = new Array();
		}
		settings['borderHorisontalWidth'] = 5;
		settings['borderVerticalWidth'] = 3;
	}
}


function _checkSize(img) {
	if(null == img){
		img = app.activeDocument;
	}
	
	var res = 0;
	if(	settings['borderHorisontalWidth'] > img.width || 
		settings['borderVerticalWidth'] > img.height )
	{
		res = -1;
	}
	return res;
}

//call this function after resize only
function _makeBorder(img) {
	if(null == img){
		img = app.activeDocument;
	}
	var leftRange = Math.round(((img.width-2) - settings['borderHorisontalWidth']) / 2) + 1;
	var upRange = Math.round(((img.height-2) - settings['borderVerticalWidth']) / 2) + 1;
	var horisontalWidth = parseInt(settings['borderHorisontalWidth']);
	var verticalWidth = parseInt(settings['borderVerticalWidth']);
		
	var selRegion = Array( 	Array(leftRange, 0), 
							Array(leftRange+horisontalWidth, 0), 
							Array(leftRange+horisontalWidth, 1), 
							Array(leftRange, 1));
	 
	img.selection.select(selRegion);
	
	
	var selRegion2 = Array( Array(0, upRange), 
							Array(1, upRange), 
							Array(1, upRange+verticalWidth), 
							Array(0, upRange+verticalWidth));
	
	img.selection.select(selRegion2, SelectionType.EXTEND);
	var color = new RGBColor();
	color.red = 0;
	color.green = 0;
	color.blue = 0;
	
	img.selection.fill(color);
	img.selection.deselect();
}

/*---------------- interface functions ----------------------*/

function Make9PatchBorder(img, silent){
	if(null == silent){
		silent = 0;
	}
	_readSettings(silent);
	
	var img = app.activeDocument;
		
	if(0 != _checkSize(img, silent)){
		return -1;
	}
	
	return _makeBorder(img);
}




